#import "FkUserAgentPlugin.h"

@implementation FkUserAgentPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"fk_user_agent"
            binaryMessenger:[registrar messenger]];
  FkUserAgentPlugin* instance = [[FkUserAgentPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getProperties" isEqualToString:call.method]) {
      [self constantsToExport:^(NSDictionary * _Nonnull constants) {
          result(constants);
      }];
  } else {
    result(FlutterMethodNotImplemented);
  }
}

@synthesize isEmulator;
@synthesize webView;

//eg. Darwin/16.3.0
- (NSString *)darwinVersion
{
    struct utsname u;
    (void) uname(&u);
    return [NSString stringWithUTF8String:u.release];
}

//eg. iPhone5,2
- (NSString *)deviceName
{
    struct utsname systemInfo;
    uname(&systemInfo);

    NSString* deviceIdentifier = [NSString stringWithUTF8String:systemInfo.machine];
    
    #if TARGET_IPHONE_SIMULATOR
        deviceIdentifier = [NSString stringWithFormat:@"%s", getenv("SIMULATOR_MODEL_IDENTIFIER")];
        self.isEmulator = YES;
    #else
        self.isEmulator = NO;
    #endif

    return deviceIdentifier;

}

- (void)getWebViewUserAgent:(void (^ _Nullable)(NSString * _Nullable webViewUserAgent, NSError * _Nullable error))completionHandler
{
    if (@available(ios 8.0, *)) {
        if (self.webView == nil) {
            // retain because `evaluateJavaScript:` is asynchronous
            self.webView = [[WKWebView alloc] init];
        }
        // Not sure if this is really neccesary
        [self.webView loadHTMLString:@"<html></html>" baseURL:nil];

        [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:completionHandler];
    }
}

- (void)constantsToExport:(void  (^ _Nullable)(NSDictionary * _Nonnull constants))completionHandler
{
    UIDevice *currentDevice = [UIDevice currentDevice];

    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"] ?: [NSNull null];
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ?: [NSNull null];
    NSString *buildNumber = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] ?: [NSNull null];
    NSString *darwinVersion = [self darwinVersion];
    NSString *cfnVersion = [NSBundle bundleWithIdentifier:@"com.apple.CFNetwork"].infoDictionary[@"CFBundleShortVersionString"];
    NSString *deviceName = [self deviceName];

    NSString *userAgent = [NSString stringWithFormat:@"CFNetwork/%@ Darwin/%@ (%@ %@/%@)", cfnVersion, darwinVersion, deviceName, currentDevice.systemName, currentDevice.systemVersion];

    [self getWebViewUserAgent:^(NSString * _Nullable webViewUserAgent, NSError * _Nullable error) {
        completionHandler(@{
          @"isEmulator": @(self.isEmulator),
          @"systemName": currentDevice.systemName,
          @"systemVersion": currentDevice.systemVersion,
          @"applicationName": appName,
          @"applicationVersion": appVersion,
          @"buildNumber": buildNumber,
          @"darwinVersion": darwinVersion,
          @"cfnetworkVersion": cfnVersion,
          @"deviceName": deviceName,
          @"packageUserAgent": [NSString stringWithFormat:@"%@/%@.%@ %@", appName, appVersion, buildNumber, userAgent],
          @"userAgent": userAgent,
          @"webViewUserAgent": webViewUserAgent ?: [NSNull null]
        });
    }];
}

@end
